// 获取模块
let gulp = require('gulp');
let cssmin = require('gulp-cssmin');
let htmlmin = require('gulp-htmlmin');
let babel = require('gulp-babel');
let gulpClean = require('gulp-clean');
let uglify = require('gulp-uglify');
let webserver = require('gulp-webserver');
const { watch } = require('gulp');

// 设置css压缩
function css() {
    return gulp.src('./src/css/**').pipe(cssmin()).pipe(gulp.dest('./dist/css'));
}

// 设置html压缩
function html() {
    return gulp.src('./src/html/**').pipe(htmlmin({
        collapseWhitespace: true, // 表示去除空格
        removeEmptyAttributes: true, // 移出空的属性
        minifyCSS: true, // 压缩 style 标签
        minifyJS: true, // 压缩 script 标签
    })).pipe(gulp.dest('./dist/html'));
};

// 设置js压缩
function js(){
    return gulp.src('./src/js/**').pipe(babel({
        presets:['env'],
    })).pipe(uglify()).pipe(gulp.dest('./dist/js'));
}

// 设置清楚缓存
function clean(){
    return gulp.src(['./dist']).pipe(gulpClean());
}

// 设置复制静态
function data(){
    return gulp.src('./src/data/**').pipe(gulp.dest('./dist/data'));
}

function images(){
    return gulp.src('./src/images/**').pipe(gulp.dest('./dist/images'));
}

// 设置监听
function watchs(){
    gulp.watch('./src/css',css);
    gulp.watch('./src/html',html);
    gulp.watch('./src/js',js);
    gulp.watch('./src/data',data);
    gulp.watch('./src/images',images);
}

// 设置开启服务
function server(){
    return gulp.src('./dist').pipe(webserver({
        host:'localhost',
        port:3000,
        open:'./html/index.html',
        livereload:true,
        proxies:[{
            source:'/api',
            target:'https://www.vvic.com',
        }],
    }))
}

// 开启服务
exports.build = gulp.series(clean,
        gulp.parallel(html,css,js,data,images),
        server,
        watchs
    )